//
//  LLQrcodeTabbar.m
//  Weibo
//
//  Created by 李灵斌 on 15-1-31.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "LLQrcodeTabbar.h"
#import "LLQrcodeItem.h"
@interface LLQrcodeTabbar ()<UINavigationControllerDelegate>

@property (nonatomic, weak) LLQrcodeItem *selectedItem;

@end

@implementation LLQrcodeTabbar

- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (void)setup{
    
    self.backgroundColor = [UIColor colorWithPatternImage:[UIImage stretchableImageWithImage:@"qrcode_tabbar_background"]];
    
    // 创建选项卡
    [self setupQrcodeItemTitle:@"二维码" image:@"qrcode_tabbar_icon_qrcode" selImage:@"qrcode_tabbar_icon_qrcode_highlighted"];
    [self setupQrcodeItemTitle:@"条形码" image:@"qrcode_tabbar_icon_barcode" selImage:@"qrcode_tabbar_icon_barcode_highlighted"];
}

// 创建选项卡
- (void)setupQrcodeItemTitle:(NSString *)title image:(NSString *)image selImage:(NSString *)selImage{
    LLQrcodeItem *item = [[LLQrcodeItem alloc] init];
    [self addSubview:item];
    [item setTitle:title forState:UIControlStateNormal];
    [item setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [item setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [item setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [item setImage:[UIImage imageNamed:selImage] forState:UIControlStateSelected];
    [item addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchDown];
    item.tag = self.subviews.count - 1;
    if (self.subviews.count == 1 ) {
        [self itemClick:item];
    }
    
}

// 点击按钮
- (void)itemClick:(LLQrcodeItem *)item{
    
    //
    if ([self.delegate respondsToSelector:@selector(qrcodeTabbarItemClick:from:to:)]) {
        [self.delegate qrcodeTabbarItemClick:self from:self.selectedItem.tag to:item.tag];
    }
    
    self.selectedItem.selected = NO;
    item.selected = YES;
    self.selectedItem = item;
}

// 布局子控件
- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    NSUInteger count = self.subviews.count;
    CGFloat itemW = self.width * 0.5;
    CGFloat itemH = self.height;
    for (int i = 0; i<count; i++) {
        
        LLQrcodeItem *item = self.subviews[i];
        item.width = itemW;
        item.height = itemH;
        item.x = i * itemW;
    }
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    if (viewController.hidesBottomBarWhenPushed) {
        self.hidden = YES;
        
    } else {
        self.hidden = NO;
    }
}


@end
